#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/10/4 9:34
# @Author  : leon yan
# @Site    :
# @File    : UserEdit.py
# @Software: PyCharm
import json

from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox
from PyQt5.QtCore import pyqtSignal, pyqtSlot

from lib.qsqledit import QSQL, NewEditDb
import Globalist as gl
from resource.UserEdit_ui import Ui_Form


class QUserEdit(QWidget, Ui_Form):
    UserUpdate = pyqtSignal()

    def __init__(self, DbId, parent=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setupUi(self)
        self.DbId = DbId
        self.UserDb = {}
        if self.DbId:
            '''Edit'''
            aa = self._rdDB()[0]
            self.accountname_le.setText(str(aa[1]))
            self.accountname_le.setDisabled(True)
            self.account_le.setText(str(aa[2]))
            self.account_le.setDisabled(True)
            self.psw_le.setText(str(aa[3]))
            self.repsw_le.setText(str(aa[3]))
            self.mobile_le.setText(str(aa[4]))
            self.mobile_le.setDisabled(True)
            self.type_le.setCurrentText(str(aa[5]))
            self.type_le.setDisabled(True)
            self.description_le.setText(str(aa[6]))
            self.description_le.setDisabled(True)
        else:
            '''New'''
            aa = self._rdDB()
            for i in range(len(aa)):
                self.UserDb[aa[i][2]] = [str(aa[i][1]), str(aa[i][3])]
            if gl.global_var["userVar"]["Admin"] == 1:
                self.type_le.setDisabled(False)
            else:
                self.type_le.setDisabled(True)

    def __del__(self):
        print("UserEdit is deleted")

    def _rdDB(self):
        aFields = ['id', 'UserName', 'LoginId', 'Password', 'Phone', 'LevelType', 'Descriptions', 'Admin']
        if self.DbId:
            strWhere = "id = " + str(self.DbId)
        else:
            strWhere = None
        obj = QSQL("UserTable", "", "", aFields, "searchOne", 1, strWhere)
        rdData = obj.showLst()
        retDataLst = json.loads(rdData)
        return retDataLst

    def _wtDB(self, lst):
        retDataLst = NewEditDb("UserTable", lst)
        return retDataLst

    @pyqtSlot()
    def on_btnClose_clicked(self):
        self.close()

    @pyqtSlot()
    def on_btnApply_clicked(self):
        UserName = self.accountname_le.text().strip()  # strip两边去空格
        LoginId = self.account_le.text().strip()  # strip两边去空格
        psw = self.psw_le.text().strip()  # strip两边去空格
        rePsw = self.repsw_le.text().strip()  # strip两边去空格
        phone = self.mobile_le.text().strip()
        LevelType = self.type_le.currentText().strip()
        description = self.description_le.text().strip()

        '''新建'''
        if self.DbId is None:
            if LoginId and LoginId in self.UserDb:  # 判断用户名是否在字典里
                QMessageBox.warning(self, "警告", "用户已存在!")
                return
            if LoginId == "" or UserName == "":
                QMessageBox.warning(self, "警告", "姓名或账号不能为空!")
                return
            if psw != rePsw or len(psw) < 6:
                QMessageBox.warning(self, "警告", "2次密码必须一直，且至少6位数，请重试!")
                return
            lst = [-1, UserName, LoginId, psw, phone, LevelType, description]
            aa = self._wtDB(lst)
            if aa:
                QMessageBox.information(self, "提示", "保存成功!")
            else:
                QMessageBox.warning(self, "警告", "保存失败!")
            self.UserUpdate.emit()
            self.close()
        else:
            '''edit'''
            if psw != rePsw or len(psw) < 6:
                QMessageBox.warning(self, "警告", "2次密码必须一直，且至少6位数，请重试!")
                return
            lst = [self.DbId, UserName, LoginId, psw, phone, LevelType, description]
            aa = self._wtDB(lst)
            if aa:
                QMessageBox.information(self, "提示", "保存成功!")
            else:
                QMessageBox.warning(self, "警告", "保存失败!")
            self.UserUpdate.emit()
            self.close()


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    EditUser_Form = QUserEdit(None)

    EditUser_Form.show()
    sys.exit(app.exec_())
